package router

import (
	"../mode"
	"fmt"
	"net/http"
	"strconv"
)

func QueryRows(w http.ResponseWriter, r *http.Request, mod int) mode.ArticleData {
	st := mode.GetArticlesStruct()
	sql := ""
	if mod == 0 {
		sql = "select a.id,a.uid,a.author,a.title,a.body,a.create_time,a.update_time,b.name as category from articles a left join category b on a.category=b.id where a.is_delete=0"
	} else {
		sql = "select a.id,a.uid,a.author,a.title,a.origin_body,a.create_time,a.update_time,b.name as category from articles a left join category b on a.category=b.id where a.is_delete=0"
	}
	countSql := "select count(*) as num from articles a left join category b on a.category=b.id where a.is_delete=0"
	indata := r.URL.Query().Get("data")
	inpage := r.URL.Query().Get("page")
	page := 1
	if inpage != "" {
		page, _ = strconv.Atoi(inpage)
	}
	switch r.URL.Query().Get("op") {
	case "all":
	case "id":
		sql += " and a.id=" + indata
	case "keyword":
		sql += " and a.name like %?% or b.name like %" + indata + "%"
		countSql += " and a.name like %?% or b.name like %" + indata + "%"
	case "category":
		sql += " and a.category=" + indata
		countSql += " and a.category=" + indata
	default:
	}
	sql += " order by a.id desc limit " + fmt.Sprint((page-1)*3) + ",3"
	rows, err := D.Query(sql)
	if err != nil {
		log.Panicln(err)
	}
	data := make([]mode.Articles, 0)
	for rows.Next() {
		rows.Scan(&st.Id, &st.Uid, &st.Author, &st.Title, &st.Body, &st.Create_time, &st.Update_time, &st.Category)
		data = append(data, *st)
	}
	row := D.QueryRow(countSql)
	var p int
	row.Scan(&p)
	aData := mode.ArticleData{
		Data:    data,
		Page:    ceil(p, 3),
		Current: page,
	}
	rows.Close()
	return aData
}
